package com.pangtuo.oss.Service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.pangtuo.oss.Service.OssService;
import com.pangtuo.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // 工具类获取值
        String endpoint = ConstantPropertiesUtils.END_POIND;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String buckeyName=ConstantPropertiesUtils.BUCKET_NAME;

        try{
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //获取上传的输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();

            //在文件名称里面添加随机唯一的值
            String uuid=UUID.randomUUID().toString().replaceAll("-","");
            fileName=uuid+fileName;

            //把文件按照日期进行分类
            String datePath=new DateTime().toString("yyyy/MM/dd");
            fileName=datePath+"/"+fileName;


            //调用oss方法实现上传
            ossClient.putObject(buckeyName, fileName, inputStream);

            ossClient.shutdown();

            //把上传到阿里云OSS路径拼接
            //https://edu-7790.oss-cn-beijing.aliyuncs.com/1.jpg
            String url="https://"+buckeyName+"."+endpoint+"/"+fileName;
            return url;

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
